<template>

    <div class="user-info">
        <!-- 系统帮助 -->
        <div class="sys-info">
            <el-button type="text" @click="openSysHelp">
                <el-tooltip class="item" effect="dark" content="系统帮助(HELP)" placement="bottom-end">
                    <el-badge class="item">
                        <i class="fa fa-question-circle" aria-hidden="true"></i>
                    </el-badge>
                </el-tooltip>
            </el-button>
        </div>

        <!-- 主题切换 -->
        <!--<div class="sys-theme">-->
        <!--<el-popover placement="top" v-model="themeVisible">-->
        <!--<div style="background-color:white;text-align: center;">-->
        <!--<span>-->
        <!--<el-button style="background-color: blue;margin: 0 10px"-->
        <!--@click="()=>{themeVisible=false;themeColor='blue';}">&nbsp;</el-button>-->
        <!--<el-button style="background-color: black;margin: 0 10px"-->
        <!--@click="()=>{themeVisible=false;themeColor='black';}">&nbsp;</el-button>-->
        <!--<el-button style="background-color: white;margin: 0 10px"-->
        <!--@click="()=>{themeVisible=false;themeColor='white';}">&nbsp;</el-button>-->
        <!--</span>-->
        <!--</div>-->
        <!--<el-button type="text" slot="reference">-->
        <!--<el-tooltip class="item" effect="dark" content="主题切换(THEME)" placement="bottom-end">-->
        <!--<el-badge class="item">-->
        <!--<i class="fa fa-tachometer" :style="{color:themeColor}" aria-hidden="true"></i>-->
        <!--</el-badge>-->
        <!--</el-tooltip>-->
        <!--</el-button>-->
        <!--</el-popover>-->
        <!--</div>-->


        <div v-if="isLogin">

            <!-- 信息数据 -->
            <div class="user-msg">
                <el-button type="text" @click="openMsg">
                    <el-tooltip class="item" effect="dark" :content="'全部：'+allIssueNumber+'；未读：'+newIssueNumber"
                                placement="bottom-end">
                        <el-badge :is-dot="newIssueNumber==0?false:true" class="item">
                            <i class="fa fa-bell" aria-hidden="true"></i>
                        </el-badge>
                    </el-tooltip>
                </el-button>
            </div>


            <!-- 用户登录信息 -->
            <div class="user-show">
                <el-dropdown :show-timeout="0" placement="bottom">
                    <el-button type="text" @click.native="enterPreOrBack">
                        <el-avatar fit="contain" :src="userInfo.img || imgSys"
                                   style="width: 30px;height: 30px"></el-avatar>
                    </el-button>
                    <el-dropdown-menu slot="dropdown">
                        <div class="dropdown-username">
                            <b>{{userInfo.alias || userInfo.username}}</b>
                        </div>
                        <el-dropdown-item @click.native="enterPreOrBack">
                            {{pageState=='pre'?'用户后台':'首页'}}
                        </el-dropdown-item>
                        <el-dropdown-item @click.native="openPersonInfo()">个人信息</el-dropdown-item>
                        <el-dropdown-item @click.native="updatePasswordHandle()">修改密码</el-dropdown-item>
                        <el-dropdown-item @click.native="logoutHandle()">退出</el-dropdown-item>
                    </el-dropdown-menu>
                </el-dropdown>
            </div>
        </div>
        <div v-else>
            <!-- 用户登录注册 -->
            <el-button icon="fa fa-user-o" plain size="mini" @click="$router.push('/login')">&nbsp;登录</el-button>
            <el-button icon="fa fa-user-plus " plain size="mini" @click="$router.push('/register')">&nbsp;注册</el-button>
        </div>


        <!-- 弹窗, 个人信息 -->
        <user-center v-if="personVisible" ref="userCenterRef"></user-center>

        <!-- 弹窗, 修改密码 -->
        <el-dialog
            title="修改密码"
            :visible.sync="visible"
            :append-to-body="true">
            <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()"
                     label-width="80px">
                <el-form-item label="账号">
                    <span>{{ userInfo.alias }}</span>
                </el-form-item>
                <el-form-item label="原密码" prop="password">
                    <el-input type="password" v-model="dataForm.password"></el-input>
                </el-form-item>
                <el-form-item label="新密码" prop="newPassword">
                    <el-input type="password" v-model="dataForm.newPassword"></el-input>
                </el-form-item>
                <el-form-item label="确认密码" prop="confirmPassword">
                    <el-input type="password" v-model="dataForm.confirmPassword"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
              <el-button @click="visible = false">取消</el-button>
              <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
            </span>
        </el-dialog>

        <!-- 消息对话框 -->
        <el-dialog title="信息列表" :visible.sync="userMsgDialog" :append-to-body="true">
            <span> {{'全部：'+allIssueNumber+'；未读：'+newIssueNumber}}</span>
            <div>
                <el-switch style="display: block" v-model="reading"
                           active-color="#13ce66"
                           inactive-color="#ff4949"
                           active-text="未读信息"
                           inactive-text="全部信息"
                           @change="refreshPageRequest(pageIndex)">
                </el-switch>
            </div>

            <el-card class="user-msg-dialog-card" v-for="userMsg in userMsgList" shadow="hover">
                <b>{{userMsg.type==1?'系统推送':userMsg.type==2?'用户评价('+userMsg.fromAlias+')':'用户留言('+userMsg.fromAlias+')'}}</b>
                &nbsp;&nbsp;<small>{{formatDate(userMsg.createTime)}}</small>
                <p v-html="userMsg.content"></p>
                <div :style="{'background-color': userMsg.isRead==0?'red':'aquamarine'}">
                    {{userMsg.isRead==0?'未读':'已读'}}
                </div>
            </el-card>

            <div class="ly-page">
                <el-pagination
                    small
                    layout="total, prev, pager, next, jumper"
                    @current-change="refreshPageRequest"
                    :current-page="pageIndex"
                    :page-size="pageSize"
                    :total="totalPage">
                </el-pagination>
            </div>

            <span slot="footer" class="dialog-footer">
              <el-button @click="userMsgDialog = false">取消</el-button>
            </span>
        </el-dialog>

        <!-- 系统帮助信息侧边栏 -->
        <el-drawer title="系统帮助文档（HELP）"
                   :visible.sync="sysInfoVisible"
                   direction="rtl"
                   :append-to-body="true">
            <el-collapse v-model="sysInfoShowContentId" accordion>
                <el-collapse-item v-for="(item,index) in sysInfoShowContent" :title="item.title" :name="index">
                    <div class="sys-info-content" v-html="item.content">
                    </div>
                </el-collapse-item>
            </el-collapse>
        </el-drawer>

    </div>

</template>

<script>
    import {clearLoginInfo} from '@/utils';
    import userCenter from '@/views/modules/sys/user-add-or-update';
    import {mapState} from 'vuex';

    export default {
        name: 'userShow',
        data() {
            let validateConfirmPassword = (rule, value, callback) => {
                if (this.dataForm.newPassword !== value) {
                    callback(new Error('确认密码与新密码不一致'));
                } else {
                    callback();
                }
            };
            return {
                dataForm: {
                    password: '',
                    newPassword: '',
                    confirmPassword: ''
                },
                dataRule: {
                    password: [
                        {required: true, message: '原密码不能为空', trigger: 'blur'}
                    ],
                    newPassword: [
                        {required: true, message: '新密码不能为空', trigger: 'blur'}
                    ],
                    confirmPassword: [
                        {required: true, message: '确认密码不能为空', trigger: 'blur'},
                        {validator: validateConfirmPassword, trigger: 'blur'}
                    ]
                },
                visible: false,

                reading: false,
                newIssueNumber: 0, //未读数量
                allIssueNumber: 0, //全部数量
                userMsgDialog: false,
                userMsgList: [],
                timer: null,
                pageIndex: 1,
                pageSize: 2,
                totalPage: 0,

                //系统帮助
                sysInfoVisible: false,
                sysInfoShowContentId: 0,
                sysInfoShowContent: [],

                //个人信息
                personVisible: false,
                imgSys: 'https://blog-yunglee.oss-cn-chengdu.aliyuncs.com/2021-06-15/0ec2865d-38fa-4b49-891c-77ef95ee757f.png',

                //主题
                themeVisible: false
            };
        },
        components: {userCenter},
        computed: {
            pageState: {
                get() {
                    return this.$store.state.common.pageState;
                },
                set(val) {
                    this.$store.commit('updatePageState', val);
                }
            },
            themeColor: {
                get() {
                    let themeColorLocal = localStorage.getItem('themeColor');
                    if (!themeColorLocal) {
                        let color = 'white';
                        localStorage.setItem('themeColor', color);
                        return color;
                    } else {
                        this.$store.commit('updateThemeColor', themeColorLocal);
                    }
                    return this.$store.state.theme.themeColor;
                },
                set(val) {
                    localStorage.setItem('themeColor', val);
                    this.$store.commit('updateThemeColor', val);
                }
            },
            ...mapState({
                userInfo: state => state.common.userInfo
            })
        },
        props: {
            isLogin: {
                type: Boolean,
                default: false
            }
        },
        methods: {
            //获取用户信息状态
            getUserMsgState() {
                this.$api.Msg.state().then((data) => {
                    if (data && data.code === 0) {
                        this.newIssueNumber = data.stateNo;
                        this.allIssueNumber = data.stateAll;
                    } else {
                        this.newIssueNumber = 0;
                    }
                });
            },
            updatePasswordHandle() {
                this.init();
            },
            openPersonInfo() {
                this.personVisible = true;
                this.$nextTick(() => {
                    this.$refs.userCenterRef.init(this.userInfo.userId, 1);
                });
            },
            // 初始化
            init() {
                this.visible = true;
                this.$nextTick(() => {
                    this.$refs['dataForm'].resetFields();
                });
            },
            // 表单提交
            dataFormSubmit() {
                this.$refs['dataForm'].validate((valid) => {
                    if (valid) {
                        this.$api.User.updatePassword({
                            'password': this.dataForm.password,
                            'newPassword': this.dataForm.newPassword
                        }).then((data) => {
                            if (data && data.code === 0) {
                                this.$message({
                                    message: '操作成功',
                                    type: 'success',
                                    duration: 1500,
                                    onClose: () => {
                                        this.visible = false;
                                        this.$nextTick(() => {
                                            this.mainTabs = [];
                                            this.$router.replace({name: 'login'});
                                        });
                                        clearLoginInfo();
                                    }
                                });
                            } else {
                                this.$message.error(data.msg);
                            }
                        }).catch(error => {
                            this.$message.error(error);
                        });
                    }
                });
            },
            logoutHandle() {
                clearInterval(this.timer);
                this.$confirm(`确定进行[退出]操作?`, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.$api.Login.logout().then((data) => {
                        if (data && data.code === 0) {
                            this.$router.push('/login');
                        }
                        clearLoginInfo();
                    });
                });
            },
            //进入前页面或者后页面
            enterPreOrBack() {
                if (this.pageState == 'pre') {
                    this.$router.push('/sys');
                    this.pageState = 'back';
                } else {
                    this.$router.push('/');
                    this.pageState = 'pre';
                }
            },

            //获取用户消息
            getUserMsg() {
                this.$api.Msg.listNo({
                    'page': this.pageIndex,
                    'limit': this.pageSize,
                    'reading': this.reading ? 1 : 0
                }).then((data) => {
                    if (data && data.code === 0) {
                        this.userMsgList = data.page.list;
                        this.totalPage = data.page.totalCount;
                    } else {
                        this.userMsgList = [];
                        this.totalPage = 0;
                    }
                });
            },

            //打开消息框
            openMsg() {
                this.userMsgDialog = true;
                this.getUserMsg();
            },
            refreshPageRequest(pageIndex) {
                this.pageIndex = pageIndex;
                this.getUserMsg();
            },

            //打开系统帮助侧边栏
            openSysHelp() {
                this.sysInfoVisible = true;
            },
            //获取系统信息
            getSysInfo() {
                this.getSysErrConfig();
            },
            //获取系统错误码信息
            getSysErrConfig() {
                this.$api.Config.listShow(1).then(res => {
                    if (res && res.code === 0) {
                        let errInfoList = res.data;
                        let errInfo = errInfoList.reduce((pre, item) => {
                            return `${pre} <b>${item.paramKey}:</b>&nbsp;${item.paramValue} <br>`;
                        }, '');
                        this.sysInfoShowContent.push({title: '错误信息编码', content: errInfo});
                    } else {
                        this.$message.error(res.msg);
                    }
                });
            }
        },
        mounted() {
            if (this.isLogin) {
                this.getUserMsgState();
            }
            let _self = this;

            timerGetUserMsg(1,1,0,0);
            //遍历实现定时服务

            /**
             * 自定义循环 通过遍历实现定时无限循环
             * factor：因子，决定定时时长
             * frequency：次数，重复次数
             * preNew：之前值
             * preAll：之前值
             * */
            function timerGetUserMsg(factor,frequency,preNew,preAll) {
                setTimeout(() => {
                    if (_self.isLogin) {
                        _self.getUserMsgState();
                        /**
                         * 重复相等 - 次数大于10
                         */
                        const cycle = 10;//周期
                        if(_self.allIssueNumber === preAll && _self.newIssueNumber === preNew && factor < cycle){
                            frequency++;
                        }else{
                            frequency = 1;
                        }
                        factor = parseInt(frequency/cycle) + 1;
                        console.log("循环因子"+factor);

                        timerGetUserMsg(factor,frequency,_self.newIssueNumber,_self.allIssueNumber);
                    }
                }, 1000 * frequency);
            }

        },
        created(){

            this.getSysInfo();
        }

    };
</script>

<style scoped>

    /* 用户 */
    .user-info {
        position: absolute;
        height: 100%;
        right: 10px;
        top: 0px;
    }

    .user-info div {

        /*flex 布局*/
        display: flex;
        /*实现垂直居中*/
        align-items: center;
        /*!*实现水平居中*!*/
        /*justify-content: center;*/

        text-align: justify;
        height: 100%;
    }

    .dropdown-username {
        text-align: center;
        margin: 10px 0px;
        padding: 5px 20px;
    }

    .user-msg {
        margin-right: 20px;
    }

    .user-msg-dialog-card {
        margin: 10px 0px;
        padding: 10px;
    }

    .user-msg-dialog-card div {
        border-radius: 50% / 50%;
        float: right;
        padding: 10px;
    }

    .user-show {
        margin-right: 10px;
    }

    /* 系统信息 */
    .sys-info, .sys-theme {
        float: right;
        padding-left: 20px;
    }

    .sys-info-content {
        padding: 15px;
    }


</style>